import React, { useState, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { useTranslation } from 'react-i18next';

const ChatWindow = () => {
  const { t } = useTranslation()

  const [chatVisible, setChatVisible] = useState(false);
  const [messages, setMessages] = useState([]);
  const [messageText, setMessageText] = useState('');


  const [userInfo] = useState(JSON.parse(localStorage.getItem('userInfo') || '{}'))

  const [socket, setSocket] = useState(null);
  const path = 'ws://47.76.182.215/prod-api/websocket/';
  let uuid = localStorage.getItem('uuid') || ''
  if (!uuid) {
    uuid = uuidv4();
    localStorage.setItem('uuid', uuid)
  }
  let wsPath = '';
  const [heartbeatInterval, setHeartbeatInterval] = useState(null);
  const [reconnectTimeout, setReconnectTimeout] = useState(null);
  //-----------------------以下是websocket部分方法

  // 初始化websocket链接
  useEffect(() => {
    if (chatVisible) {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        if (userInfo.userId === undefined) {
          wsPath = path + uuid;
        } else {
          wsPath = path + userInfo.userId;
        }
        const ws = new WebSocket(wsPath);
        ws.addEventListener('open', (event) => {
          console.log('WebSocket connection opened:', event);
          startHeartbeat(ws);
        });
        ws.addEventListener("message", (event) => { onmessage(event) });
        ws.addEventListener('error', (event) => {
          console.error('WebSocket error:', event);
          handleConnectionError(ws);
        });
        ws.addEventListener('close', (event) => {
          console.log('WebSocket connection closed:', event);
          stopHeartbeat();
          handleConnectionClose(ws);
        });
        setSocket(ws);
      }
    }

    // 清理操作 - 当组件卸载时关闭WebSocket连接
    return () => {
      stopHeartbeat();
      clearReconnectTimeout();
      // socket.close();
    };
  }, [chatVisible]);

  const startHeartbeat = (ws) => {
    const intervalId = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send("ping");
      } else {
        clearInterval(intervalId);
      }
    }, 5000); // 每5秒发送一次心跳包

    setHeartbeatInterval(intervalId);
  };

  const stopHeartbeat = () => {
    clearInterval(heartbeatInterval);
  };

  const handleConnectionError = (ws) => {
    console.log('WebSocket connection error, attempting to reconnect...');
    reconnect(ws);
  };

  const handleConnectionClose = (ws) => {
    console.log('WebSocket connection closed, attempting to reconnect...');
    reconnect(ws);
  };
  const reconnect = () => {
    clearReconnectTimeout();
    const timeoutId = setTimeout(() => {
      console.log('Attempting to reconnect...');
      const newWs = new WebSocket(wsPath);
      newWs.addEventListener('open', (event) => {
        console.log('WebSocket reconnected:', event);
        startHeartbeat(newWs);
      });
      newWs.addEventListener('message', (event) => onmessage(event));
      newWs.addEventListener('error', (event) => {
        console.error('WebSocket error:', event);
        handleConnectionError(newWs);
      });
      newWs.addEventListener('close', (event) => {
        console.log('WebSocket connection closed:', event);
        stopHeartbeat();
        handleConnectionClose(newWs);
      });
      setSocket(newWs);
    }, 5000); // 每5秒尝试重新连接一次
    setReconnectTimeout(timeoutId);
  };

  const clearReconnectTimeout = () => {
    clearTimeout(reconnectTimeout);
  };
  //接受后台信息回调
  const onmessage = (e) => {
    /**这里写自己的业务逻辑代码**/
    console.log("收到后台信息:", e.data);
    if (e.data === 'pong') {
      //收到服务器信息，心跳重置
    } else {
      let msg = JSON.parse(e.data)
      if (msg.msgType === 1) {
        const rmessage = {
          text: msg.msg,
          type: 'received'
        };
        setMessages((prevMessages) => [...prevMessages, rmessage]);
      }
    }
  };
  const toggleChat = () => {
    setChatVisible(!chatVisible);
  };

  const sendMessage = (event) => {
    event.preventDefault();
    if (messageText.trim() === '') return;

    // Add sent message
    const newMessage = {
      text: messageText,
      type: 'sent',
    };
    setMessages([...messages, newMessage]);
    setMessageText('');

    let message = {
      msg: messageText
    }
    socket.send(JSON.stringify(message));
    // // Play send sound
    // const sendSound = new Audio('https://www.soundjay.com/button/beep-07.wav');
    // sendSound.play();
    //
    // setTimeout(() => {
    //     const receivedMessage = {
    //         id: '客服',
    //         text: '客服已收到您的消息。',
    //         type: 'received',
    //     };
    //     setMessages((prevMessages) => [...prevMessages, receivedMessage]);
    //
    //     // Play receive sound
    //     const receiveSound = new Audio('https://www.soundjay.com/button/beep-08b.wav');
    //     receiveSound.play();
    // }, 1000);
  };

  return (
    <div className='overflow-visible'>
      {/*<div*/}
      {/*  className="fixed bottom-5 m-0 right-5 bg-[#5A866E] sm:text-[16px] text-[10px] text-white rounded-lg sm:p-3 p-1.5 cursor-pointer shadow-lg hover:bg-[#508068] hover:scale-110 transition-transform duration-300"*/}
      {/*  onClick={toggleChat}>*/}
      {/*  💬 {t('24小时在线客服')}*/}
      {/*</div>*/}
      {/* Chat Window */}
      {chatVisible && (<div
        className="fixed sm:bottom-20 bottom-14 right-5 w-80 max-w-full bg-white border border-gray-300 shadow-lg rounded-lg overflow-hidden">
        <div className="bg-[#5A866E] text-white p-4 text-center font-bold">
          {t('在线客服')}
        </div>
        <div className="h-80 overflow-y-auto p-4" id="chatMessages">
          {messages.map((message, index) => (<div key={index}
            className={`message mb-4 flex flex-col ${message.type === 'sent' ? 'items-end' : 'items-start'}`}>
            <div className="text-xs text-gray-500 mb-1">{message.id}</div>
            <div className="flex items-center">
              {message.type === 'received' && (<div className="text-2xl mr-2">🤖</div>)}
              <div
                className={`p-3 rounded-lg max-w-xs ${message.type === 'sent' ? 'bg-[#5A866E] text-white' : 'bg-gray-100'}`}>
                {message.text}
              </div>
              {message.type === 'sent' && (
                <div className="text-2xl ml-2">👤</div>
              )}
            </div>
          </div>
          ))}
        </div>

        {/* Chat Input */}
        <form className="flex border-t border-gray-300" onSubmit={sendMessage}>
          <input
            type="text"
            value={messageText}
            onChange={(e) => setMessageText(e.target.value)}
            className="flex-1 p-2 outline-none"
            placeholder={t('输入消息...')}
          />
          <button
            type="submit"
            className="bg-[#5A866E] text-white p-2"
          >
            {t('发送')}
          </button>
        </form>
      </div>
      )}
    </div>
  );
};

export default ChatWindow;
